package org.dragonnova.lamp;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import org.dragonnova.lamp.message.IProtocol;
import org.dragonnova.lamp.message.Protocol;
import org.dragonnova.lamp.service.IService;
import org.dragonnova.lamp.service.UDPService;

import java.util.List;

/**
 * Created by hucn on 2016/10/25.
 * Description: 控制灯的入口
 */
public class LampController {

    private volatile static LampController instance;

    private IService mService;
    private MessageDelivery mDelivery;
    private LampManager mLampManager;

    public static LampController getInstance(Context context) {
        if (instance == null) {
            synchronized (LampController.class) {
                if (instance == null) {
                    instance = new LampController(context);
                }
            }
        }
        return instance;
    }

    private LampController(Context context) {
        if (context == null) {
            throw new IllegalArgumentException("The context is null");
        }

        context = context.getApplicationContext();
        IProtocol protocol = new Protocol();
        mDelivery = new defaultDelivery(new Handler(Looper.getMainLooper()));
        mLampManager = new LampManager();
        mService = new UDPService(context, protocol, mDelivery, mLampManager);
    }

    public void setLampListener(LampListener listener) {
        mDelivery.setLampListener(listener);
    }

    public void start() {
        mService.stop();
        mService.start();
    }

    public void discovery() {
        mService.discovery();
    }

    public void control(Lamp lamp, int status) {
        if (lamp.getStatus() == status) {
            return;
        }
        mService.control(lamp, status);
    }

    public void stop() {
        mService.stop();
        clearLamps();
    }

    public void clearLamps() {
        mLampManager.clear();
    }

    public List<Lamp> getLamps() {
        return mLampManager.getLamps();
    }
}
